package com.wlts.wzy.configBean.shiro;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlts.wzy.DYUserModule.entity.DyStoreUser;
import com.wlts.wzy.DYUserModule.service.IDyStoreUserService;
import com.wlts.wzy.KSUserModule.entity.KsStoreUser;
import com.wlts.wzy.KSUserModule.service.IKsStoreUserService;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.sys_shiro.entity.SysUser;
import com.wlts.wzy.sys_shiro.service.impl.SysUserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserServiceImpl usersService;

    @Autowired
    private IKsStoreUserService ksStoreUserService;

    @Autowired
    private IDyStoreUserService dyStoreUserService;
//

    /**
     * 用于获取登录成功后的角色、权限等信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //@RequiresRoles("admin")
        System.out.println("进入角色授权");
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(principalCollection.getPrimaryPrincipal()));
        String userName = jsonObject.getString("name");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SysAuthorizationInfo personInfo = usersService.getAuthor(userName);

        System.out.println(personInfo);
        if (personInfo != null) {
            if (personInfo.getRoles().size() > 0) {
                info.setRoles(personInfo.getRoles());
                info.setStringPermissions(personInfo.getPermissions());
            }
        }

        System.out.println(JSON.toJSONString(info));

        return info;
    }

    /**
     * 验证当前登录的Subject
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //拿到账号（username）
        String username = (String) token.getPrincipal();
        //检查token的信息

        System.out.println(username);

        String[] params = username.split("\\|");

        SimpleAuthenticationInfo authenticationInfo;

        if (params.length > 1) {
            /**
             * 微信登录
             */
            if (params[1].equals("ks")) {

                // System.out.println("登录" + params[0]);

                MyLambdaQueryWrapper<KsStoreUser> myLambdaQueryWrapper = new MyLambdaQueryWrapper<>();

                myLambdaQueryWrapper.eq(KsStoreUser::getDelFlag, "0");

                myLambdaQueryWrapper.eq(KsStoreUser::getName, params[0]);

                KsStoreUser xcxUser = ksStoreUserService.getOne(myLambdaQueryWrapper);

                if (xcxUser == null) {
                    return null;
                }

             //   System.out.println(xcxUser.toString());

                authenticationInfo = new SimpleAuthenticationInfo(
                        xcxUser, //用户名
                        xcxUser.getPassword(), //密码
                        ByteSource.Util.bytes(xcxUser.getUuid() + xcxUser.getPassword()),//salt=username+salt
                        xcxUser.getUuid()  //realm name
                );
                //authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
                return authenticationInfo;
                //authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
            }
            /**
             * 微信登录
             */
            if (params[1].equals("dy")) {

                // System.out.println("登录" + params[0]);

                MyLambdaQueryWrapper<DyStoreUser> myLambdaQueryWrapper = new MyLambdaQueryWrapper<>();

                myLambdaQueryWrapper.eq(DyStoreUser::getDelFlag, "0");

                myLambdaQueryWrapper.eq(DyStoreUser::getName, params[0]);

                DyStoreUser xcxUser = dyStoreUserService.getOne(myLambdaQueryWrapper);

                if (xcxUser == null) {
                    return null;
                }

                //   System.out.println(xcxUser.toString());

                authenticationInfo = new SimpleAuthenticationInfo(
                        xcxUser, //用户名
                        xcxUser.getPassword(), //密码
                        ByteSource.Util.bytes(xcxUser.getUuid() + xcxUser.getPassword()),//salt=username+salt
                        xcxUser.getUuid()  //realm name
                );
                //authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
                return authenticationInfo;
                //authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
            }


        }
        /**
         * 总端登录
         */
        SysUser user = usersService.getOne(new QueryWrapper<SysUser>().eq("name", username));
        if (user == null) {
            return null;
        }

        authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户名
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getName() + user.getSalt()),//salt=username+salt
                getName()  //realm name
        );
        //authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return authenticationInfo;
    }
}
